package com.chat.socketServer;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chat.enums.EventName;
import com.chat.enums.EventType;
import com.chat.enums.SocketMethodEnum;
import com.chat.po.Event;
import com.chat.service.UserService;

@ServerEndpoint("/SocketServer")
public class SocketServer {
	
	private UserService userService = new UserService();
	
	public SocketServer() {
	}
	
	@OnOpen
	public void onOpen(Session session) {
		System.out.println("链接开启："+session.getId());
	}
	@OnClose
	public void onClose(Session session) {
		System.out.println("链接关闭："+session.getId());
		OnlineUserManager.logOut(session);
	}
	@OnError
    public void onError(Throwable t) throws Throwable {
	      System.out.println(t.toString());
    }
	@OnMessage
	public void onMessage(String message, Session session) {
		System.out.println(message);
		handleMsg(message,session);
	}

	/**
	 * 功能：处理消息
	 * 时间：2016年7月1日下午4:51:41
	 * @author 杨建全
	 * @param message 字符消息
	 * @param session Session
	 */
	private void handleMsg(String message, Session session) {
		JSONObject msgJson = JSON.parseObject(message);
		String methodName = msgJson.getString("methodName");
		Event retEvent = null;
		if (methodName!=null) {
			switch (methodName) {
				//登录
				case SocketMethodEnum.LOGIN:
					retEvent = userService.login(msgJson,session);
					break;
				case SocketMethodEnum.SendAllMsg:
					retEvent = userService.sendALLMsg(msgJson,session);
					break;
				default:
					retEvent = new Event(EventName.UnKnow, EventType.EVENT);
					break;
			}
			Send(session, JSON.toJSONString(retEvent));
		}else{
			retEvent = new Event(EventName.UnKnow, EventType.EVENT, "服务器消息：链接到服务器成功。但methrodName为空！");
			Send(session, JSON.toJSONString(retEvent));
		}
	}
	
	public static synchronized void Send(Session session,String msg){
		try {
			if(session!=null&&session.isOpen()){
				session.getBasicRemote().sendText(msg);
			}
		} catch (Exception e) {
			
		}
	}
}